<template>
    <div>
        <el-card>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>商品分类</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="btnBox">
                <div>
                    <el-button size="small" @click="addHandle">添加分类</el-button>
                </div>
            </div>
            <el-table :data="classifyList" style="width: 100%" row-key="productCategoryId"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" height="626" lazy :load="load">
                <el-table-column type="index" label="#" width="50">
                </el-table-column>
                <el-table-column prop="categoryName" label="商品分类"></el-table-column>
                <el-table-column label="分类图片">
                    <template slot-scope="prop">
                        <el-image :src="prop.row.categoryImg" class="image-control"
                            :previewSrcList="[prop.row.categoryImg]"></el-image>
                    </template>
                </el-table-column>
                <!-- categoryImg -->

                <el-table-column label="是否有效" center>
                    <template slot-scope="scope">
                        <i class="el-icon-success" v-if="scope.row.categoryStatus == '1'"></i>
                        <i class="el-icon-error" v-else></i>
                    </template>
                </el-table-column>
                <el-table-column prop="pai" label="排序">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.categoryLevel == '0'">一级</el-tag>
                        <el-tag type="success" v-else-if="scope.row.categoryLevel == '1'">二级</el-tag>
                        <el-tag type="warning" v-else-if="scope.row.categoryLevel == '2'">三级</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="380">
                    <template slot-scope="scope">
                        <el-button size="small" icon="el-icon-edit" @click="editHandle(scope.row)">编辑</el-button>
                        <el-button size="small" icon="el-icon-upload2" @click="statusHandle(1, scope.row)"
                            v-if="scope.row.categoryStatus == '0'">上架</el-button>
                        <el-button size="small" icon="el-icon-download" @click="statusHandle(0, scope.row)"
                            v-if="scope.row.categoryStatus == '1'">下架</el-button>
                        <el-button size="small" icon="el-icon-plus" @click="addChild(scope.row)"
                            v-if="scope.row.categoryLevel == '0'">添加二级分类</el-button>
                        <!-- <el-button size="small" icon="el-icon-plus" @click="addChild(scope.row)"
                            v-if="scope.row.categoryLevel == '1'">添加三级分类</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加弹窗 -->
        <el-dialog title="添加" :visible.sync="addialogVisible" width="36%" :before-close="closeAddDialog">
            <el-form :model="form" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="上级分类" prop="classifyValue" v-if="addFlag == 'all'">
                    <el-select size="small" filterable v-model="form.classifyValue" @change="getC"
                        placeholder="请选择上级分类">
                        <el-option :label="item.categoryName" :value="item.productCategoryId"
                            v-for="(item, index) in classifyList" :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称">
                    <div>
                        <el-button size="small" @click="nameHandle('add')">添加分类</el-button>
                        <el-button size="small" @click="nameHandle('del')">删除分类</el-button>
                    </div>
                    <div v-for=" (item, index) in form.classifyNameList" :key="index"
                        style="display: flex;align-items: center;margin-bottom: 16px;">
                        <el-checkbox v-model="item.checked" style="margin-right: 16px"></el-checkbox>
                        <span>分类{{ index + 1 }}：</span>
                        <el-input size="small" v-model="item.cName" placeholder="请输入分类名称"
                            style="width: 220px;"></el-input>
                        <div class="uploadBox" @click="getIndex(index)" v-if="form.classifyValue == 0">
                            <div class="imgListBox" v-if="item.classPicUrl">
                                <div>
                                    <el-image :src="item.classPicUrl" class="avatar avatar1"
                                        :previewSrcList="[item.classPicUrl]"></el-image>
                                    <div class="closeBox" @click="delImg(index)">
                                        <i class="el-icon-circle-close"></i>
                                    </div>
                                </div>
                            </div>
                            <el-upload v-else action="aa" class="avatar-uploader avatar-uploader1"
                                :on-change="imgChange" :auto-upload="false" accept=".jpg,.png" ref="addProduct_pic"
                                :show-file-list="false">
                                <i class="el-icon-plus avatar-uploader-icon avatar-uploader-icon1"></i>
                            </el-upload>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddDialog">取 消</el-button>
                <el-button type="primary" @click="submitAddDialog">确 定</el-button>
            </span>
        </el-dialog>



        <!-- 修改分类名-->
        <el-dialog title="修改" :visible.sync="editDia" width="30%" :before-close="closeEditDialog">
            <el-form :model="editForm" label-width="100px">
                <el-form-item label="分类名称">
                    <el-input v-model="editForm.categoryName" placeholder="请输入分类名称"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeEditDialog">取 消</el-button>
                <el-button type="primary" @click="submitEdit">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { addCategory, getProductCategory, updateCategoryName, updateCategoryStatus, addFirstCategory } from '../../network/classify'
export default {
    data() {
        return {
            addialogVisible: false,//弹窗
            classifyList: [],

            form: {
                classifyValue: 0,
                classifyNameList: [
                    {
                        cName: '',
                        checked: false,
                        classPic: '',
                        classPicUrl: ''
                    },

                ],
            },
            rules: {
                classifyValue: [
                    { required: true, message: '请选择上级分类', trigger: 'change' },
                ],
            },
            editDia: false,
            editForm: {
                categoryId: '',
                categoryName: '',
            },
            addFlag: 'all',// all 顶部添加 可选择分类  one 按钮添加 不可选择

            selectIndex: -1,
        };
    },
    methods: {
        getIndex(index) {
            console.log(index);
            this.selectIndex = index
        },
        // 上传图片
        imgChange(file) {
            // console.log(index);
            console.log(file);

            let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            console.log(fileType);

            if (
                fileType == 'jpg' ||
                fileType == 'png'
            ) {
                this.form.classifyNameList[this.selectIndex].classPicUrl = URL.createObjectURL(file.raw);
                this.form.classifyNameList[this.selectIndex].classPic = file.raw;
            } else {
                // 提醒只能上传的文件类型
                this.$message.warning('只能上传jpg或png文件')
                return;
            }

        },

        delImg(index) {
            console.log(index);
            this.form.classifyNameList[index].classPicUrl = ''
            this.form.classifyNameList[index].classPic = ''
        },
        addChild(obj) {
            this.addFlag = 'one'
            console.log(obj);
            if (obj.parentId != 0) {
                this.form.classifyValue = obj.parentId
            }

            this.form.classifyValue = obj.productCategoryId
            this.addialogVisible = true
        },


        getList() {
            getProductCategory({
                parentId: 0,
                companyId: sessionStorage.companyId,
            }).then(res => {
                if (res.flag) {
                    console.log(res);
                    var list = res.data
                    // 获取一级分类
                    list.forEach((item, index) => {
                        item.children = []
                        item.index = index
                        item.hasChildren = true
                    })
                    this.classifyList = res.data
                    console.log(this.classifyList);
                }
            })
        },


        // 获取下一级分类
        async load(tree, treeNode, resolve) {
            console.log(treeNode);
            console.log(tree);
            const children = await this.getChild(tree.productCategoryId, tree.categoryLevel);
            resolve(children)
        },

        getChild(id, level) {
            console.log(level);
            return new Promise((resolve) => {
                getProductCategory({
                    parentId: id,
                    companyId: sessionStorage.companyId,
                }).then(res => {
                    if (res.flag) {
                        console.log(res);
                        var list = res.data
                        // 获取二级分类
                        list.forEach((item, index) => {
                            item.children = []
                            item.index = index
                            item.level = 1
                            item.hasChildren = false
                        })
                        resolve(list);
                    }
                })
            });
        },

        // 添加分类
        addHandle() {
            this.classifyList.unshift({
                productCategoryId: 0,
                categoryName: '一级分类'
            },)
            this.addialogVisible = true
            this.addFlag = 'all'
        },

        // 选择商品分类
        selectProClassify(value) {
            console.log(value);
            this.form.classifyValue = value
        },

        detailHandle(obj) {
            console.log(obj);
        },
        getC() {
            console.log(this.form);
        },
        submitAddDialog() {
            this.$refs.addForm.validate((valid) => {
                if (!valid) return
                var flag = false,
                    form = this.form,
                    list = this.form.classifyNameList;
                console.log(form);
                console.log(this.form);


                var parentId = form.classifyValue,
                    categoryNames = '', flag = parentId == 0 ? 0 : 1, isEmpty = false;

                form.classifyNameList.forEach(ele => {

                    if (ele.classPicUrl == '') {
                        isEmpty = true
                    }

                    if (ele.cName != '') {
                        categoryNames += ele.cName + ','
                    }
                })


                console.log(parentId);
                console.log(categoryNames);
                console.log(flag);

                if (categoryNames == '') {
                    this.$message.warning('请输入分类名称')
                    return
                }


                if (flag == 0 && isEmpty) {
                    this.$message.warning('请上传分类图片')
                    return
                }
                console.log(this.form);

                if (flag == 0) {

                    let fd = new FormData();
                    list.forEach((ele, index) => {
                        fd.append(`file`, ele.classPic);
                        fd.append(`categoryList[${index}].categoryName`, ele.cName);
                        fd.append(`categoryList[${index}].categoryStatus`, 1);
                        fd.append(`categoryList[${index}].parentId`, 0);
                        fd.append(`categoryList[${index}].categoryLevel`, 0);
                        fd.append(`categoryList[${index}].companyId`, sessionStorage.companyId);
                    })

                    addFirstCategory(fd).then(res => {
                        if (res.flag) {
                            this.$message.success('添加成功')
                            this.$forceUpdate()
                            this.getList()
                            this.closeAddDialog()
                        } else {
                            this.$message.warning('添加失败')
                        }
                    })

                } else if (flag == 1) {  //添加 二级分类
                    addCategory({
                        parentId,
                        categoryNames,
                        flag,
                        companyId: sessionStorage.companyId,
                    }).then(res => {
                        if (res.flag) {
                            this.$message.success('添加成功')
                            this.$forceUpdate()
                            this.getList()
                            this.closeAddDialog()
                        } else {
                            this.$message.warning('添加失败')
                        }
                    })
                }



            });

        },

        // 启用 禁用 分类
        statusHandle(flag, obj) {
            updateCategoryStatus({
                Ids: obj.productCategoryId,
                status: flag
            }).then(res => {
                if (res.flag) {
                    this.$message.success('操作成功')
                    this.getList()
                } else {
                    this.$message.warning('操作失败')
                }
            })
        },


        editHandle(obj) {
            this.editForm.categoryId = obj.productCategoryId
            this.editForm.categoryName = obj.categoryName
            this.editDia = true

            console.log(this.editForm);
        },


        closeEditDialog() {
            this.editDia = false
        },
        submitEdit() {
            if (this.editForm.categoryName == '') {
                this.$message.warning('请输入分类名称')
                return
            }

            updateCategoryName(this.editForm).then(res => {
                if (res.flag) {
                    this.$message.success('修改成功')
                    this.getList()
                    this.closeEditDialog()
                } else {
                    this.$message.warning('修改失败')
                }
            })
        },
        // 关闭弹窗
        closeAddDialog() {
            this.addialogVisible = false
            this.classifyList.shift()
            this.form = {
                classifyValue: [],
                classifyNameList: [
                    {
                        cName: '',
                        checked: false,
                        classPic: '',
                        classPicUrl: ''
                    }
                ],
            }

        },


        // 添加分类名 删除分类名
        nameHandle(flag) {
            if (flag == 'add') {
                this.form.classifyNameList.push({
                    checked: false,
                    cName: '',
                    classPic: '',
                    classPicUrl: ''
                })
            } else {
                if (this.form.classifyNameList.length == 1) {
                    this.$message.warning('最少添加一个分类')
                    return
                }
                var arr = this.form.classifyNameList.filter(item => {
                    return item.checked
                })
                console.log(arr);
                if (arr.length == 0) {
                    this.$message.warning('请勾选要删除的分类')
                    return
                }
                this.form.classifyNameList = this.form.classifyNameList.filter(item => {
                    return !item.checked
                })

            }
        },

    },
    created() {
        this.getList()
    },
    filters: {

    },
};
</script>

<style scoped>
.el-icon-success {
    color: aquamarine;
    font-size: 18px;
}

.el-icon-error {
    color: red;
    font-size: 18px;
}



.imgListBox,
.uploadBox {
    display: flex;
    align-content: center;
}

.closeBox {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
    height: 20px;
    background-color: rgba(0, 0, 0, .5);
    color: #fff;
    border-radius: 4px;
    cursor: pointer;
    z-index: 10;
}

.playBtn {
    position: absolute;
    top: 34px;
    left: 34px;
    font-size: 32px;
    color: #fff;
}

.imgListBox>div {
    position: relative;
    margin-right: 16px;
}

.el-upload__tip {
    color: red;

}

.videoBox {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}


.videoCon {
    width: 500px;
    height: 500px;
}

.formatBox {
    display: flex;
    align-items: center;
    width: 100%;

}

.formatBox>div>.el-input {
    width: 150px;
}

.formatBox>div {
    margin: 16px 0 0 16px;
    display: flex;
    align-items: center;
}

.avatar-uploader1,
.avatar-uploader-icon1,
.avatar1 {
    margin-left: 16px;
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
}

.addBtn {
    font-size: 18px;
    margin-left: 16px;
    color: #999;
    cursor: pointer;
}


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #dcdfe6;
    border-radius: 8px;
}

.avatar {

    width: 100px;
    height: 100px;
    display: block;
}


.image-control {
    width: 80px;
    height: 80px;
}
</style>